#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include <gtk/gtk.h>
#include<stdlib.h>
#include "support.h"
#include "addgroup.h"
#include "message.h"
#include "string.h"
#include "file.h"
#include "clist.h"
#include "newinfo.h"

struct addgroup_struct addgroup;
/*
 * callbacks for add gourp dialog(four below)
 */
void
on_button_add_group_cancel_clicked     (GtkButton       *button,
                                        gpointer         user_data)
{
	GtkWidget *window_add_group=(GtkWidget *)user_data;
	gtk_widget_destroy(window_add_group);
}

void
on_button_add_group_ok_clicked         (GtkButton       *button,
                                        gpointer         user_data)
{
	struct addgroup_struct *addgroup=(struct addgroup_struct *)user_data;
	struct file_ctrl *global_file=addgroup->global_file;
	struct clist_struct *clist=addgroup->clist;
	struct file_list *add,*last;
	gchar *info[2];
	gint i,len;
	#ifdef _DEBUG_
		printf("on_button_add_group_ok_clicked :---\n");
	#endif
	info[0]=(const gchar *)gtk_entry_get_text(GTK_ENTRY(addgroup->entry_name));
	for(i=0,len=strlen(info[0]);i<len;i++) {
		if(info[0][i]==' ')
			info[0][i]='-';
	}
	if(len==0) {
		on_button_add_group_help_clicked (NULL,addgroup->window);
		return;
	}
	if(len>=30) {
		gchar msg[]="输入的组名不能大于30个字符!";
		message_box_for_add_group(addgroup->window,msg);
		return;
	}
	info[1]="0";
	for(last=global_file->files;last->next!=NULL;last=last->next) {
		if(strcmp(info[0],last->name)==0||strcmp(info[0],last->newname)==0) {
			gchar msg[]="输入的组名已经存在!";
			message_box_for_add_group(addgroup->window,msg);
			return;
		}
	}
	strncpy(global_file->current,info[0],FILE_NAME_LEN);
	strncpy(last->name,info[0],FILE_NAME_LEN);
	create_data_file(global_file->data,last->name);
	create_data_file(global_file->tmp,last->name);
	read_data_file_info(last,global_file->data);
	add=(struct file_list *)malloc(sizeof(struct file_list));
	memset(add,'\0',sizeof(struct file_list));
	last->next=add;
	add->next=NULL;
	last->group_id=global_file->group_nums;
	gtk_clist_append(GTK_CLIST(clist->clist_group),(gchar **)info);
	global_file->modify=TRUE;
	global_file->data_mod=TRUE;
	*clist->group_all_row += 1;
	gtk_clist_select_row(GTK_CLIST(clist->clist_group),last->group_id,0);
	gtk_widget_destroy(addgroup->window);	
}

void
on_window_add_group_destroy            (GtkObject       *object,
                                        gpointer         user_data)
{
	gtk_widget_destroy(GTK_WIDGET(object));
}


void
on_button_add_group_help_clicked       (GtkButton       *button,
                                        gpointer         user_data)
{
	gchar msg[]="请输入一个分组的名称！";
	message_box_for_add_group(addgroup.window,msg);
}
